// 假设你已经有一个信令服务器的socket连接
const socket = io();
const videoGrid = document.getElementById('video-grid');
const myVideo = document.createElement('video');
myVideo.muted = true;

navigator.mediaDevices.getUserMedia({ video: true, audio: true })
    .then(stream => {
        const configuration = { iceServers: [{ urls: 'stun:118.25.18.233:3478' }] };
        const peerConnection = new RTCPeerConnection(configuration);

        addVideoStream(myVideo, stream);

        stream.getTracks().forEach(track => {
            console.log('stream', stream);
            peerConnection.addTrack(track, stream);
        });

        peerConnection.onicecandidate = event => {
            if (event.candidate) {
                socket.emit('ice-candidate', event.candidate);
            }
        };

        peerConnection.createOffer()
            .then(offer => peerConnection.setLocalDescription(offer))
            .then(() => {
                socket.emit('offer', peerConnection.localDescription);
            })
            .catch(error => {
                console.error('Error creating offer:', error);
            });

        socket.on('answer', answer => {
            peerConnection.setRemoteDescription(answer);
        });

        socket.on('ice-candidate', candidate => {
            peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
        });
    })
    .catch(error => {
        console.error('Error accessing media devices.', error);
    });

function addVideoStream(video, stream) {
    video.srcObject = stream;
    video.addEventListener('loadedmetadata', () => {
        video.play();
    });
    videoGrid.append(video);
}